﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using RuTracker.Interface.Login;
using RuTracker.MVC.Models.Login;
using RuTracker.Interface;
using RuTracker.MVC.Core;

namespace RuTracker.MVC.Controllers
{
    public class AuthorizeController : Controller
    {
        #region inner classes
        class TempdataReaderWriter
        {
            private readonly TempDataDictionary _dataDictionary;

            public TempdataReaderWriter(TempDataDictionary dataDictionary)
            {
                _dataDictionary = dataDictionary;
            }

            public string CaptchaUrl
            {
                get { return _dataDictionary["CaptchaUrl"] as string; }
                set { _dataDictionary["CaptchaUrl"] = value; }
            }

            public LoginResults LastLoginResults
            {
                get { return _dataDictionary["LastLoginResults"] as LoginResults; }
                set { _dataDictionary["LastLoginResults"] = value; }
            }
        }

        #endregion

        public ActionResult Index()
        {
            LogoutInternal();
            LoginModel model = new LoginModel();
            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(LoginModel model)
        {
            if (!ModelState.IsValid)
                return View(model);

            TempdataReaderWriter tempdataReaderWriter = new TempdataReaderWriter(TempData);
            LoginProcessing loginDataContext = new LoginProcessing(Request, Response);
            LoginResults loginResults = loginDataContext.ProcessLogin(model, tempdataReaderWriter.LastLoginResults);

            tempdataReaderWriter.CaptchaUrl = loginResults.CaptchaUrl;
            tempdataReaderWriter.LastLoginResults = loginResults;
            model.IsCaptchaRequired = loginResults.IsCaptchaRequired;

            if (loginResults.Succeeded)
                return RedirectToAction("Index", "Default");

            return View(model);
        }

        public ActionResult Logout()
        {
            LogoutInternal();

            return RedirectToAction("Index");
        }

        private void LogoutInternal()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();

            // clear authentication cookie
            HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
            cookie1.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie1);

            // clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
            HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
            cookie2.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie2);

            ICookiesContainer cookiesContainer = Container.Current.Resolve<ICookiesContainer>();
            cookiesContainer.Reset();
        }

        public ActionResult GetCapture()
        {
            TempdataReaderWriter tempdataReaderWriter = new TempdataReaderWriter(TempData);
            string captchaUrl = tempdataReaderWriter.CaptchaUrl;

            if (string.IsNullOrEmpty(captchaUrl))
                return new EmptyResult();

            try
            {
                IWebClient webClient = Container.Current.Resolve<IWebClient>();
                byte[] buffer = webClient.DownloadData(captchaUrl);
                return new FileContentResult(buffer, "image/jpeg");
            }
            catch (Exception)
            {
                return new EmptyResult();
            }
        }
    }
}
